//
//  SinaWeibo.m
//  YuiKe
//
//  Created by yuike5 yuike5 on 11-10-24.
//  Copyright 2011年 yuike. All rights reserved.
//

#import "SinaWeibo.h"
#import "MBProgressHUD.h"
#import "WeiboCommentNode.h"
#import "NSString+Extension.h"
#import "HTTPUtil.h"
#import "Logger.h"
#import "UserData.h"


@interface SinaWeibo(Private)
- (void)thisDidReceive:(WBEngine*)sender obj:(NSObject*)obj error:(NSError*)error;
@end



@implementation SinaWeibo
@synthesize short_url_shorten_autorelease;
@synthesize max_callback_shorten_url_share_statuses_count;


// key 丢失的时候，可以从服务端修改
#define kOAuthConsumerKey		g_sina_key
#define kOAuthConsumerSecret	g_sina_secret


#define API_TYPE_WeiboAuthDelegate 1 // 从1开始编号
#define API_TYPE_WeiboCommitDelegate 2
#define API_TYPE_WeiboGetFriendshipDelegate 3
#define API_TYPE_WeiboFollowDelegate 4
#define API_TYPE_WeiboGetUserInfoDelegate 5
#define API_TYPE_WeiboShortUrlClicksDelegate 6
#define API_TYPE_WeiboShortUrlShortenDelegate 7
#define API_TYPE_WeiboShortUrlShareCountsDelegate 8
#define API_TYPE_WeiboShortUrlShareStatusDelegate 9
#define API_TYPE_WeiboShortUrlCommentCountsDelegate 10
#define API_TYPE_WeiboShortUrlCommentCommentsDelegate 11
#define API_TYPE_WeiboSearchDelegate 12
#define API_TYPE_WeiboCommentsShowDelegate 13
#define API_TYPE_WeiboCommentCreateDelegate 14
#define API_TYPE_WeiboNodeShowDelegate 15
#define API_TYPE_WeiboFriendsDelegate   16

#define API_TYPE_short_url_clicks_bylong 17
#define API_TYPE_short_url_clicksArray_bylong 18
#define API_TYPE_short_url_share_counts_bylong 19
#define API_TYPE_short_url_share_statuses_bylong 20
#define API_TYPE_short_url_comment_counts_bylong 21
#define API_TYPE_short_url_comment_comments_bylong 22

#define API_TYPE_WeiboShortUrlShortenArrayDelegate 23
#define API_TYPE_WeiboShortUrlClicksArrayDelegate 24



//#define YRelease(x) [x release], x=nil;
static NSString* g_sina_key = nil;
static NSString* g_sina_secret = nil;
static NSString* g_sina_nick = nil;
+(void) setDefaultKey:(NSString*)key andSecret:(NSString*)secret {
    YRelease(g_sina_key)
    YRelease(g_sina_secret)
    g_sina_key = [key copy];
    g_sina_secret = [secret copy];
}
+(void) setSinaWeiboAtNick:(NSString*)nick {
    YRelease(g_sina_nick)
    g_sina_nick = [nick copy];
}



static NSMutableSet* g_ClicksCache_urlShort = nil;
+(void) clearClicksCache {
    if (g_ClicksCache_urlShort)
        [g_ClicksCache_urlShort removeAllObjects];
}
+(void) addClicksCachebyUrlShort:(NSString*)url_short {
    if (g_ClicksCache_urlShort == nil)
        g_ClicksCache_urlShort = [[NSMutableSet alloc] init];
    [g_ClicksCache_urlShort addObject:url_short];
}
+(BOOL) isVisitedbyUrlShort:(NSString*)url_short {
    if (g_ClicksCache_urlShort == nil) 
        return false;
    return [g_ClicksCache_urlShort containsObject:url_short];
}
+(void) short_url_click:(NSString*)short_url {
    
    if ([NSString isNilOrEmpty:short_url]) {
        return;
    }
    
    /*_url_short*/ 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
        NSURL* url = [NSURL URLWithString:short_url]; 
        NSData* data = [HTTPUtil dataResultFromGetRequestWithURL:url parameters:nil additionalHeaderFields:nil timeoutInterval:10.0 response:nil error:nil]; 
        
        if (data) 
        {
            NSString* page = [NSString stringWithUTF8String:data.bytes]; 
            int idx = MIN(page.length, 24);
            page = [page substringToIndex:idx];
            DebugLog(@"Goodplus(%@) -- \"%@\"", short_url, page);
            data = nil; 
            page = nil; 
        }
     
        /* dispatch_async(dispatch_get_main_queue(), ^{HTTPUtil */ 
        /* }); */ 
    });
}
+(void) short_url_click_bylong:(NSString*)long_url {
    if (!long_url || long_url.length<=0) return;
    NSString* url_short = [[UserDataforUrlmap sharedInstance] getShortUrlByLongUrl:long_url];
    if (url_short != nil) {
        [SinaWeibo short_url_click:url_short];
        return;
    }    
    SinaWeibo* sw = [[SinaWeibo alloc] init];
    sw.short_url_shorten_autorelease = true;
    [sw short_url_shorten:long_url delegate:sw];
}



-(void) getNode:(id<WeiboNodeShowDelegate>)delegate_ urlid:(NSString*)urlid
{
    // 3413794443243803
    // y5MR6dBRp
    long long idx = [[SinaWeibo url2mid:urlid] longLongValue];
    //urlid = [SinaWeibo mid2url:[SinaWeibo url2mid:urlid]]; for test
    return [self getNode:delegate_ idx:idx];
}
-(void) getCommentsSINAv1:(id<WeiboCommentsShowDelegate>)delegate_ 
                    urlid:(NSString*)urlid
                    count:(int)count
                     page:(int)page
{
    long long idx = [[SinaWeibo url2mid:urlid] longLongValue];
    return [self getCommentsSINAv1:delegate_ idx:idx count:count page:page];
}


-(NSArray*)emotions
{
    NSMutableArray* array = [[[NSMutableArray alloc ] init ] autorelease];
    for (NSString* temp in [
                            // 精简，，，有些 表情 不适合 购物推荐的。-- 太多了 用户看不清楚。
                            @"zz2_org.gif|[织],horse2_org.gif|[神马],fuyun_org.gif|[浮云],geili_org.gif|[给力],wg_org.gif|[围观],vw_org.gif|[威武],panda_org.gif|[熊猫],rabbit_org.gif|[兔子],otm_org.gif|[奥特曼],j_org.gif|[囧],hufen_org.gif|[互粉],liwu_org.gif|[礼物],smilea_org.gif|[呵呵],tootha_org.gif|[嘻嘻],laugh.gif|[哈哈],tza_org.gif|[可爱],kl_org.gif|[可怜],kbsa_org.gif|[挖鼻屎],cj_org.gif|[吃惊],shamea_org.gif|[害羞],zy_org.gif|[挤眼],bz_org.gif|[闭嘴],bs2_org.gif|[鄙视],lovea_org.gif|[爱你],sada_org.gif|[泪],heia_org.gif|[偷笑],qq_org.gif|[亲亲],sb_org.gif|[生病],mb_org.gif|[太开心],ldln_org.gif|[懒得理你],yhh_org.gif|[右哼哼],zhh_org.gif|[左哼哼],x_org.gif|[嘘],cry.gif|[衰],wq_org.gif|[委屈],t_org.gif|[吐],k_org.gif|[打哈气],bba_org.gif|[抱抱],angrya_org.gif|[怒],yw_org.gif|[疑问],cza_org.gif|[馋嘴],88_org.gif|[拜拜],sk_org.gif|[思考],sweata_org.gif|[汗],sleepya_org.gif|[困],sleepa_org.gif|[睡觉],money_org.gif|[钱],sw_org.gif|[失望],cool_org.gif|[酷],hsa_org.gif|[花心],hatea_org.gif|[哼],gza_org.gif|[鼓掌],dizzya_org.gif|[晕],bs_org.gif|[悲伤],crazya_org.gif|[抓狂],h_org.gif|[黑线],yx_org.gif|[阴险],nm_org.gif|[怒骂],hearta_org.gif|[心],unheart.gif|[伤心],pig.gif|[猪头],ok_org.gif|[ok],ye_org.gif|[耶],good_org.gif|[good],no_org.gif|[不要],z2_org.gif|[赞],come_org.gif|[来],sad_org.gif|[弱],lazu_org.gif|[蜡烛],clock_org.gif|[钟],cake.gif|[蛋糕],m_org.gif|[话筒]"
                            
                            // 筛选掉 比较悲观的 表情 系列。。。保留 乐观的
                            //@"geili_org.gif|[给力],vw_org.gif|[威武],panda_org.gif|[熊猫],rabbit_org.gif|[兔子],otm_org.gif|[奥特曼],liwu_org.gif|[礼物],smilea_org.gif|[呵呵],tootha_org.gif|[嘻嘻],laugh.gif|[哈哈],tza_org.gif|[可爱],cj_org.gif|[吃惊],shamea_org.gif|[害羞],lovea_org.gif|[爱你],heia_org.gif|[偷笑],qq_org.gif|[亲亲],mb_org.gif|[太开心],yhh_org.gif|[右哼哼],zhh_org.gif|[左哼哼],x_org.gif|[嘘],bba_org.gif|[抱抱],cza_org.gif|[馋嘴],sk_org.gif|[思考],money_org.gif|[钱],cool_org.gif|[酷],hsa_org.gif|[花心],hatea_org.gif|[哼],gza_org.gif|[鼓掌],hearta_org.gif|[心],ok_org.gif|[ok],ye_org.gif|[耶],good_org.gif|[good],z2_org.gif|[赞],come_org.gif|[来],cake.gif|[蛋糕]"
                            
                            
                            componentsSeparatedByString:@","]) {
        NSArray* a = [temp componentsSeparatedByString:@"|"];
        
        WeiboEmotion* e = [[[WeiboEmotion alloc ] init] autorelease];
        e.phrase= [a objectAtIndex:1];
        e.localName = [a objectAtIndex:0];
        [array addObject:e];
    }
    return array;
}
-(NSArray*)urlStringsforCookies {
    return [NSArray arrayWithObjects:
            // 1.0
            @"http://weibo.com/", 
            @"http://api.weibo.com/", 
            @"http://open.weibo.com/", 
            @"http://t.sina.com/", 
            @"http://t.sina.com.cn/", 
            @"http://api.t.sina.com.cn/", 
            @"http://open.t.sina.com.cn/", 
            // 2.0
            @"https://api.weibo.com/2/",
            @"https://api.weibo.com/oauth2/access_token",
            @"https://api.weibo.com/oauth2/authorize",
            nil];
}

-(id) init
{
    self = [super init];
    if (self) {
        // Initialization code here.
        if (!_engine){            
            _engine = [[WBEngine alloc] initWithAppKey:kOAuthConsumerKey appSecret:kOAuthConsumerSecret];
            [_engine setDelegate:self];
            [_engine setRedirectURI:@"http://"];
            [_engine setIsUserExclusive:NO];
            
        }
        //if (!_engine.OAuthSetup) [_engine requestRequestToken];
//        draft = [[Draft alloc] initWithType:DraftTypeNewTweet];
        _array = [[NSMutableArray alloc] init];
        
        [self isAuthorized];
    }
    
    return self;
}
-(NSString*) title
{
    return @"新浪微博";
}
-(NSString*) cpsUrlTrans:(NSString*)cpsUrl { 

    NSString* temp = [[UserDataforUrlmap sharedInstance] getShortUrlByLongUrl:cpsUrl];
    if (temp)
        return temp;
    
    NSString* cpsUrl1 = [cpsUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return cpsUrl1;
};
-(int) theSnsId
{
    return SNS_ID_SINA_WEIBO;
}
-(UIImage*) theIcon32x32
{
    return [UIImage imageNamed:@"sina_weibo_32x32.png"];
}
-(UIImage*) theIcon48x48
{
    return [UIImage imageNamed:@"sina_weibo_48x48.png"];
}
-(NSString*) _protected_nick 
{
    return g_sina_nick;
}


-(void) dealloc
{
    _engine.delegate = nil;
    [_engine release];
    _engine = nil;
    
    [step_ShortUrl setDelegateNilAll];
    YRelease(step_ShortUrl)
    
    for (WeiboClient *client in _array)
        [client setDelegateNil];
    [_array release];
//    [draft release];
    [super dealloc];
}

-(void) cancelAll {
    [self setDelegateNilAll];
    for (WeiboClient *client in  _array) {
        [client cancel];
    }
}

-(BOOL) isAuthorized
{
    // 重现加载帐号，因为可能已经 xxx-- 存在问题 "error_code":"401","error":"40113:token_rejected!"
   // BOOL ret = [[[[OAuthEngine alloc] initOAuthWithDelegate: self] autorelease] isAuthorized];
   // return ret;
    //return [_engine isAuthorized];
    [self reloadAuthInfo];
    return [_engine isLoggedIn] && ![_engine isAuthorizeExpired];
}




-(void) auth:(id<WeiboAuthDelegate>)delegate_
{
    // 防御。。。
    [_engine logOut]; // 防御。。。
    
    self.authDelegate = delegate_;

    UIWebView* authview = [self.authDelegate weiboAuthview];
    self.authDelegateBackup = authview.delegate;
    authview.delegate = self;    
    [_engine logIn: authview];
}



#pragma mark - WBEngineDelegate Methods

- (void)engine:(WBEngine *)engine requestDidSucceedWithResult:(id)result
{
    [self thisDidReceive:engine obj:result error:nil];
}

- (void)engine:(WBEngine *)engine requestDidFailWithError:(NSError *)error
{
    [self thisDidReceive:engine obj:nil error:error];
}

- (void)thisDidReceive:(WBEngine*)sender obj:(NSObject*)obj error:(NSError*)error
{
    // 如果失效。。。
    if (sender.isAuthError) {
        [self signOutx];
    }

    if (_apiType == API_TYPE_WeiboShortUrlClicksDelegate) {
        
        if (sender.hasError) {
            [self.getWeiboShortUrlClicksDelegate getWeiboShortUrlClicksError:self];
            return;
        }
        
        if (obj == nil || ![obj isKindOfClass:[NSDictionary class]]) {
            [self.getWeiboShortUrlClicksDelegate getWeiboShortUrlClicksError:self];
            return;
        }
        
        NSArray * array = (NSArray *) [obj valueForKey:@"urls"];
        for (NSDictionary * dic in array) {
            NSString * url_short = [dic valueForKey:@"url_short"];
            NSString* url_long = [dic valueForKey:@"url_long"];
            int clicks = [[dic valueForKey:@"clicks"] intValue]; 
            if (clicks < 0) clicks = 0;
            // 数据库的数据，只能变大，不能变小，就没有 联网失败 造成的疑惑了。。。
            int db_clicks = [[UserDataforClicksbak sharedInstance] getClicks:url_long];
            if (clicks < db_clicks)
                clicks = db_clicks;
            if (clicks > db_clicks && clicks>0) // 缓存起来。
                [[UserDataforClicksbak sharedInstance] setClicks:url_long clicks:clicks];
            
            [SinaWeibo addClicksCachebyUrlShort:url_short];
            [self.getWeiboShortUrlClicksDelegate getWeiboShortUrlClicksCallback:self url_short:url_short url_long:url_long clicks:clicks];
        }        
    }   
    
    else if (_apiType == API_TYPE_WeiboShortUrlClicksArrayDelegate) {
        
        if (sender.hasError) {
            [self.getWeiboShortUrlClicksArrayDelegate getWeiboShortUrlClicksArrayError:self];
            return;
        }
        
        if (obj == nil || ![obj isKindOfClass:[NSDictionary class]]) {
            [self.getWeiboShortUrlClicksArrayDelegate getWeiboShortUrlClicksArrayError:self];
            return;
        }
        
        NSArray * array = (NSArray *) [obj valueForKey:@"urls"];
        NSMutableDictionary* mdict = [NSMutableDictionary dictionary];
        for (NSDictionary * dic in array) {
            NSString * url_short = [dic valueForKey:@"url_short"];
            NSString* url_long = [dic valueForKey:@"url_long"];
            int clicks = [[dic valueForKey:@"clicks"] intValue]; 
            if (clicks < 0) clicks = 0;
            // 数据库的数据，只能变大，不能变小，就没有 联网失败 造成的疑惑了。。。
            int db_clicks = [[UserDataforClicksbak sharedInstance] getClicks:url_long];
            if (clicks < db_clicks)
                clicks = db_clicks;
            if (clicks > db_clicks && clicks>0) // 缓存起来。
                [[UserDataforClicksbak sharedInstance] setClicks:url_long clicks:clicks];
            
            [SinaWeibo addClicksCachebyUrlShort:url_short];
            WeiboUrlClicksResult* value = [[WeiboUrlClicksResult alloc] initWithUrlLong:url_long urlShort:url_short clicks:clicks];
            [mdict setValue:value forKey:url_short];
        }
        [self.getWeiboShortUrlClicksArrayDelegate getWeiboShortUrlClicksArrayCallback:self short2clicks_dict:mdict];
    }

    
    else if (_apiType == API_TYPE_WeiboNodeShowDelegate) {
        
        //{"request":"/statuses/show/:id.json","error_code":"400","error":"40031:Error: target weibo does not exist!"}
        if (sender.hasError) {
            [self.getWeiboNodeShowDelegate getWeiboError:self];
            return;
        }
        if (obj == nil || ![obj isKindOfClass:[NSDictionary class]]) {
            [self.getWeiboNodeShowDelegate getWeiboError:self];
            return;
        }
        
        NSDictionary* dict = (NSDictionary*) obj;
        WeiboNode* node = [[[WeiboNode alloc] initWithSinaWeibo:dict] autorelease];
        [self.getWeiboNodeShowDelegate getWeiboCallback:self result:node];
        return;
    }
    
    
    else if (_apiType == API_TYPE_WeiboCommentCreateDelegate) {
        
        if (obj!=nil && [obj isKindOfClass:[NSDictionary class]]) {
            NSDictionary* dict = (NSDictionary*) obj;
            
            NSString* request = [dict valueForKey:@"request"];
            NSString* error_code = [dict valueForKey:@"error_code"];
            NSString* error = [dict valueForKey:@"error"];
            
            //{"request":"/statuses/comment.json","error_code":"400","error":"40025:Error: repeated weibo text!"}
            if (request!=nil && 
                ([request compare:@"/statuses/comment.json"]==0 || false)
                &&
                error_code!=nil && [error_code compare:@"400"]==0 &&
                error!=nil && [[error substringToIndex:6] compare:@"40025:"]==0) {
                
                [self.getWeiboCommentCreateDelegate createCommentCallback:self idx:self.backupCommentIdx result:NULL];
                return;
            }
            
            // {"request":"/statuses/comment.json","error_code":"400","error":"40031:target weibo does not exist!"}
            if (error != nil) {
                [self.getWeiboCommentCreateDelegate createCommentError:self reason:error];
                return;
            }
        }
        
        if (sender.hasError) {
            [self.getWeiboCommentCreateDelegate createCommentError:self reason:NULL];
            return;
        }
        //http://open.weibo.com/wiki/Statuses/comment
        NSDictionary* dict = (NSDictionary*) obj;
        WeiboCommentNode* node = [[WeiboCommentNode alloc] initWithSinaComment:dict];
        [node autorelease];
        [self.getWeiboCommentCreateDelegate createCommentCallback:self idx:self.backupCommentIdx result:node];
        return;
    }
    
    else if (_apiType == API_TYPE_WeiboGetUserInfoDelegate) {
        if (sender.hasError) {
            [self.getWeiboGetUserInfoDelegate getUserInfoError: self];
            return;
        }
        if (obj == nil || ![obj isKindOfClass:[NSDictionary class]]) {
            [self.getWeiboGetUserInfoDelegate getUserInfoError: self];
            return;
        }
        NSDictionary *dict = (NSDictionary*)obj;
        WeiboUserNode* node = [[[WeiboUserNode alloc] initWithSinaUser:dict] autorelease];
        
        NSString* screenName = node.screen_name;
        NSString* domain = [node sinaDomain];
        domain = [@"http://weibo.com/" stringByAppendingString:domain]; // // 这行不变，有算法依赖，根据这个取 weibobase domain
        [self.getWeiboGetUserInfoDelegate getUserInfoCallback:self nick:screenName domain:domain user:node];
    }
    
    else if (_apiType == API_TYPE_WeiboCommentsShowDelegate) {
        if (sender.hasError) {
            [self.getWeiboCommentsShowDelegate getCommentsError: self];
            return;
        }
        if (obj == nil || ![obj isKindOfClass:[NSArray class]]) {
            [self.getWeiboCommentsShowDelegate getCommentsError: self];
            return;
        }
        NSArray *array = (NSArray*)obj;
        long total_number = -1;//[[dict valueForKey:@"total_number"] longValue];
        
        NSArray* comments = array;//[dict valueForKey:@"comments"];
        NSMutableArray* iComments = [[[NSMutableArray alloc] init ] autorelease]; 
        for (NSDictionary* dict in comments) {
            WeiboCommentNode* node = [[WeiboCommentNode alloc] initWithSinaComment:dict];
            [iComments addObject: node];
            [node autorelease];
        }
        [self.getWeiboCommentsShowDelegate getCommentsCallback:self totalnum:total_number alist:iComments];
    }
    
    else if (_apiType == API_TYPE_WeiboSearchDelegate) {
        if (sender.hasError) {
            [self.getWeiboSearchDelegate searchError: self];
            return;
        }
        if (obj == nil || ![obj isKindOfClass:[NSDictionary class]]) {
            [self.getWeiboSearchDelegate searchError: self];
            return;
        }
        //    NSDictionary *dict = (NSDictionary*)obj;
        //    NSDictionary *source = [dict valueForKey:@"source"];
        //    [self.searchDelegate searchCallback:self];
    }
    
    else if (_apiType == API_TYPE_WeiboFollowDelegate) {
        if (sender.hasError) {		
            
            //2011-10-28 19:23:32.529 YuiKe[6073:12803] followDidReceive error!!!, 
            //errorMessage:Weibo Server Error, 
            //errordetail:40303:Error: already followed
            /*if (sender.errorDetail == 40303) {
             [self.delegate followCallback:self idx:self.follow_idx_bak result:YES];
             return;
             }*/
            
            DebugLog(@"followDidReceive error!!!, errorMessage:%@, errordetail:%@"
                  , sender.errorMessage, sender.errorDetail);
            [self.getWeiboFollowDelegate followCallback:self idx:self.backupFollowIdx result:NO];
            return;
        }
        
        if (obj == nil || ![obj isKindOfClass:[NSDictionary class]]) {
            DebugLog(@"followDidReceive data format error.%@", @"");
            [self.getWeiboFollowDelegate followCallback:self idx:self.backupFollowIdx result:NO];
            return;
        }    
        
        NSDictionary *dic = (NSDictionary*)obj;
        User *responseUser = [[[User alloc]initWithJsonDictionary:dic] autorelease];
        DebugLog(@"follow user success:.%@", responseUser.screenName);
        [self.getWeiboFollowDelegate followCallback:self idx:responseUser.userId result:YES];
    }
    
    else if (_apiType == API_TYPE_WeiboCommitDelegate) {
        if (sender.hasError) {
            // v2.0 对重复发送微薄的识别
            if (error && error.userInfo) {
                int error_code = [[error.userInfo valueForKey:@"error_code"] intValue];
                NSString* _error = [error.userInfo valueForKey:@"error"];
                if (error_code == 20019 && [@"repeat content!" compare:_error] == 0) {
                    [self.getWeiboCommitDelegate commitCallback:self]; 
                    return;
                }
            }
            
            // v1.0
            //{"request":"/statuses/upload.json","error_code":"400",
            //"error":"40028:不要太贪心哦！你已经发过一次啦。"}
            if (obj!=nil && [obj isKindOfClass:[NSDictionary class]]) {
                NSDictionary* dict = (NSDictionary*) obj;
                
                NSString* request = [dict valueForKey:@"request"];
                NSString* error_code = [dict valueForKey:@"error_code"];
                NSString* error = [dict valueForKey:@"error"];
                if (request!=nil && 
                    ([request compare:@"/statuses/upload.json"]==0 || [request compare:@"/statuses/update.json"]==0)
                    &&
                    error_code!=nil && [error_code compare:@"400"]==0 &&
                    error!=nil && [[error substringToIndex:6] compare:@"40028:"]==0) {
                    
                    [self.getWeiboCommitDelegate commitCallback:self]; 
                    return;
                }
                
                //http://open.weibo.com/wiki/Error_code
                if (request!=nil &&
                    error_code!=nil && [error_code compare:@"400"]==0 &&
                    error!=nil) {
                    [self.getWeiboCommitDelegate commitCallbackError:self reason:error];
                    return;
                }
            }
            
            //[sender alert];	
            [self.getWeiboCommitDelegate commitCallbackError:self reason:nil]; 
            return;
        }
        
        NSDictionary *dic = nil;
        if (obj && [obj isKindOfClass:[NSDictionary class]]) {
            dic = (NSDictionary*)obj;    
        }
        
        if (dic) {
            Status* sts = [Status statusWithJsonDictionary:dic];
            if (sts) {
            }
        }
        [self.getWeiboCommitDelegate commitCallback:self]; 
    }
    
    else if (_apiType == API_TYPE_WeiboGetFriendshipDelegate) {
        if (sender.hasError) {
            [self.getWeiboGetFriendshipDelegate getFriendshipError: self];
            return;
        }
        if (obj == nil || ![obj isKindOfClass:[NSDictionary class]]) {
            [self.getWeiboGetFriendshipDelegate getFriendshipError: self];
            return;
        }
        NSDictionary *dict = (NSDictionary*)obj;
        NSDictionary *source = [dict valueForKey:@"source"];
        //NSDictionary *target = [dict valueForKey:@"target"];
        NSNumber* following =  [source valueForKey:@"following"];
        NSNumber* followed_by = [source valueForKey:@"followed_by"];
        [self.getWeiboGetFriendshipDelegate getFriendshipCallback:self following:following.boolValue followedBy:followed_by.boolValue];
    }
    
    else if (_apiType == API_TYPE_WeiboFriendsDelegate) {
        if (sender.hasError) {
            [self.getWeiboFriendsDelegate getWeiboFriendsError:self];
            return;
        }
        if (obj == nil || ![obj isKindOfClass:[NSDictionary class]]) {
            [self.getWeiboFriendsDelegate getWeiboFriendsError:self];
            return;
        }
        NSDictionary *dict = (NSDictionary*)obj;
        NSArray* users = [dict valueForKey:@"users"];
        
        NSMutableArray* array = [[[NSMutableArray alloc] init ] autorelease];
        for (NSDictionary* user in users) {
            WeiboUserNode* node = [[[WeiboUserNode alloc] initWithSinaUser:user] autorelease];
            [array addObject:node];
        }
        [self.getWeiboFriendsDelegate getWeiboFriendsCallback:self alist:array hasNext:array.count>=self.backupgetFriendsReqnum nextCursor:-1];
    }
    //[self assertDelegateNilAll]; // 必须回调，形成闭环，这里检查一次。顺便
    else if (_apiType == API_TYPE_WeiboShortUrlShareStatusDelegate) {
        if (sender.hasError) {
            [self.getWeiboShortUrlShareStatusDelegate getWeiboShortUrlShareStatusDelegateError:self];
            return;
        }
        
        if (!obj || ![obj isKindOfClass:[NSObject class]]) {
            [self.getWeiboShortUrlShareStatusDelegate getWeiboShortUrlShareStatusDelegateError:self];
            return;
        }
        
//dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* url_short = [obj valueForKey:@"url_short"];  
        if (![url_short startswith:@"http://"])
            url_short = [NSString stringWithFormat:@"http://t.cn/%@", url_short];
        NSString* url_long = [obj valueForKey:@"url_long"];
        NSObject* share_statuses = [obj valueForKey:@"share_statuses"];
        
            
        NSMutableArray * result = [[[NSMutableArray alloc] initWithCapacity:1] autorelease];
    if (share_statuses && [share_statuses isKindOfClass:[NSArray class]]) {
        NSArray * array = (NSArray *) share_statuses;
        for (NSDictionary * dic in array) {
            WeiboNode* node = [[[WeiboNode alloc] initWithSinaWeibo:dic] autorelease];     
            node.text = [node.text replace:url_short with:@" "].strip; // 不显示短网址
            node.text = [node.text replace:self.rootNick with:@" "].strip;            
            if (node.text && node.text.length>0 && [node.text compare:@"转发微博"]!=0 && [node.text compare:@"转发微博。"]!=0 && !node.sina_deleted) {
                if (max_callback_shorten_url_share_statuses_count<=0 || 
                        (max_callback_shorten_url_share_statuses_count>0 &&
                         result.count<max_callback_shorten_url_share_statuses_count)) { // 处理最多回显示个数 控制
                    [result addObject:node];
                } else {
                    break;
                }
            }
        }    
    }
//    dispatch_async(dispatch_get_main_queue(), ^{
        [self.getWeiboShortUrlShareStatusDelegate getWeiboShortUrlShareStatusDelegateCallback:self url_short:url_short url_long:url_long share_statuses:result];
//    });
//});
    }
    
    else if (_apiType == API_TYPE_WeiboShortUrlCommentCommentsDelegate) {
        if (sender.hasError) {
            [self.getWeiboShortUrlCommentCommentsDelegate getWeiboShortUrlCommentCommentsDelegateError:self];
            return;
        }
        if (!obj || ![obj isKindOfClass:[NSObject class]]) {
            [self.getWeiboShortUrlCommentCommentsDelegate getWeiboShortUrlCommentCommentsDelegateError:self];
            return;
        }
        NSString* url_short = [obj valueForKey:@"url_short"];   
        if (![url_short startswith:@"http://"])
            url_short = [NSString stringWithFormat:@"http://t.cn/%@", url_short];
        NSString* url_long = [obj valueForKey:@"url_long"];
        NSObject* share_comments = [obj valueForKey:@"share_comments"];
        
        NSArray * array = (NSArray *) share_comments;        
        NSMutableArray * result = [[[NSMutableArray alloc] initWithCapacity:1] autorelease];
        for (NSDictionary * dic in array) {
            WeiboCommentNode* node = [[[WeiboCommentNode alloc] initWithSinaComment:dic] autorelease];  
            node.text = [node.text replace:url_short with:@" "]; // 不显示短网址
            node.text = [node.text replace:self.rootNick with:@" "];
            [result addObject:node];
        }               
        [self.getWeiboShortUrlCommentCommentsDelegate getWeiboShortUrlCommentCommentsDelegateCallback:self url_short:url_short url_long:url_long share_comments:result];
    }
    
    else if(_apiType == API_TYPE_WeiboShortUrlShortenDelegate) 
    {
        if (sender.hasError) {
            [self.getWeiboShortUrlShortenDelegate getWeiboShortUrlShortenDelegateError:self];
            return;
        }
        
        if (obj == nil || ![obj isKindOfClass:[NSDictionary class]]) {
            [self.getWeiboShortUrlShortenDelegate getWeiboShortUrlShortenDelegateError:self];
            return;
        }
        
        NSArray * array = (NSArray *) [obj valueForKey:@"urls"];
        for (NSDictionary * dic in array) {
            NSString * url_short = [dic valueForKey:@"url_short"];
            NSString* url_long = [dic valueForKey:@"url_long"];
            bool result = [[dic valueForKey:@"result"] boolValue];
//            DebugLog(@"API_TYPE_WeiboShortUrlShortenDelegate %@ %@ %@", url_long, url_short, [dic valueForKey:@"result"]);
            result = true;
            
            if (url_long && url_long.length>0 && url_short && url_short.length>0) {
                [[UserDataforUrlmap sharedInstance] bakUrlLong:url_long urlShort:url_short];
            }
            [self.getWeiboShortUrlShortenDelegate getWeiboShortUrlShortenDelegateCallback:self url_short:url_short url_long:url_long result:result];
        }        
    }
    
    else if (_apiType == API_TYPE_WeiboShortUrlShortenArrayDelegate) {
        if (sender.hasError) {
            [self.getWeiboShortUrlShortenArrayDelegate getWeiboShortUrlShortenArrayDelegateError:self];
            return;
        }
        
        if (obj == nil || ![obj isKindOfClass:[NSDictionary class]]) {
            [self.getWeiboShortUrlShortenArrayDelegate getWeiboShortUrlShortenArrayDelegateError:self];
            return;
        }
        
        NSArray * array = (NSArray *) [obj valueForKey:@"urls"];
        NSMutableDictionary* mdict = [NSMutableDictionary dictionary];
        for (NSDictionary * dic in array) {
            NSString * url_short = [dic valueForKey:@"url_short"];
            NSString* url_long = [dic valueForKey:@"url_long"];
            bool result = [[dic valueForKey:@"result"] boolValue];
            //            DebugLog(@"API_TYPE_WeiboShortUrlShortenDelegate %@ %@ %@", url_long, url_short, [dic valueForKey:@"result"]);
            result = true;
            
            if (url_long && url_long.length>0 && url_short && url_short.length>0) {
                [[UserDataforUrlmap sharedInstance] bakUrlLong:url_long urlShort:url_short];
            }
            
            WeiboUrlShortenResult* value = [[[WeiboUrlShortenResult alloc] initWithUrlLong:url_long urlShort:url_short result:result] autorelease];
            [mdict setValue:value forKey:url_long];
        }      
        [self.getWeiboShortUrlShortenArrayDelegate getWeiboShortUrlShortenArrayDelegateCallback:self long2short_dict:mdict];
    }
}


-(void) getFriends:(id<WeiboFriendsDelegate>)delegate_ page:(int)page reqnum:(int)reqnum
{
    assert(reqnum <= 50);
    [self setOnetimeDelegate: delegate_];    
    _apiType = API_TYPE_WeiboFriendsDelegate; 
    self.backupgetFriendsReqnum = reqnum;
    [_engine api_getFriendshipsFriendsBilateral:[_engine.userID longLongValue] count:reqnum page:page];
}

-(int) getFriendsFirstIntvalue {
    return 1; // 第一页
}

-(int) getFriendsMaxReqnum {
    return 50;
}



-(void) getUserInfo:(id<WeiboGetUserInfoDelegate>)delegate_
{
    [self setOnetimeDelegate: delegate_];
    _apiType = API_TYPE_WeiboGetUserInfoDelegate;
    [_engine api_getUsersShow:[_engine.userID longLongValue]];
}

-(void) getCommentsSINAv1:(id<WeiboCommentsShowDelegate>)delegate_ 
                      idx:(long long)idx
                    count:(int)count
                     page:(int)page
{
    [self setOnetimeDelegate: delegate_];
    self.backupGetCommentsIdx = idx;
    //API_TYPE_WeiboCommentsShowDelegate
}

-(void) search:(id<WeiboSearchDelegate>)delegate_ qvalue:(NSString*)qvalue
{
    [self setOnetimeDelegate: delegate_];
    //API_TYPE_WeiboSearchDelegate
}
-(void) comment:(id<WeiboCommentCreateDelegate>)delegate_ idx:(long long)idx  comment:(NSString*)comment
{
    [self setOnetimeDelegate: delegate_];
    self.backupCommentIdx = idx;
    //[client comment:idx comment:comment];
    //API_TYPE_WeiboCommentCreateDelegate
    //[client comment:idx commentId:0 comment:comment];
}

-(void) getNode:(id<WeiboNodeShowDelegate>)delegate_ idx:(long long)idx
{
    [self setOnetimeDelegate: delegate_];
    // v2.0
    _apiType = API_TYPE_WeiboNodeShowDelegate;
    [_engine api_getStatusesShow:idx];
}



//[UIImageJPEGRepresentation(attachmentImage, 0.8) retain];
-(void) commit:(id<WeiboCommitDelegate>)delegate_ content:(NSString *)content image:(UIImage*)image
{
    [self setOnetimeDelegate: delegate_];
    content = [content stringByReplacingOccurrencesOfString:self.rootNick withString:self.nick];
    // 规整
    while ([content rangeOfString:@"  "].location != NSNotFound)
       content = [content replace:@"  " with:@" "].strip;
    // v2.0
    _apiType = API_TYPE_WeiboCommitDelegate;
    [_engine sendWeiBoWithText:content image:image];
}

-(void) follow:(id<WeiboFollowDelegate>)delegate idx:(long long)idx
{
    self.backupFollowIdx = idx;
    [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_WeiboFollowDelegate;
    [_engine api_postFriendshipsCreate:idx];
}
-(void) getFriendship:(id<WeiboGetFriendshipDelegate>)delegate_ idx:(long long)idx
{
    [self setOnetimeDelegate: delegate_]; // v2.0
    _apiType = API_TYPE_WeiboGetFriendshipDelegate;
    [_engine api_getFriendshipsShow_source_id:[_engine.userID longLongValue] target_id:idx];
}




-(void) _protected_signOut
{
    [_engine logOut];
}


-(void) reloadAuthInfo
{
    [_engine readAuthorizeDataFromKeychain];
    [self loadCurrentUserInfo];
}



//=============================================================================================================================
#pragma mark Webview Delegate stuff
- (void) webViewDidFinishLoad: (UIWebView *) webView {
    [super webViewDidFinishLoad:webView]; 
}

- (void) webViewDidStartLoad: (UIWebView *) webView {
    [super webViewDidStartLoad:webView];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [super webView:webView didFailLoadWithError:error];
}

- (BOOL) webView: (UIWebView *) webView shouldStartLoadWithRequest: (NSURLRequest *) request 
  navigationType: (UIWebViewNavigationType) navigationType {
    
    [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    
    
    if (true) { // v2.0
        NSRange range = [request.URL.absoluteString rangeOfString:@"code="];
        
        if (range.location != NSNotFound)
        {
            NSString *code = [request.URL.absoluteString substringFromIndex:range.location + range.length];
            // if not canceled
            if (![code isEqualToString:@"21330"]) {
                [_engine requestAccessTokenWithAuthorizeCode:code]; // 转一次
            }
        }
        
        return YES;
    }
    
    // v1.0
    //DebugLog(@"auth request(callback): %@", [request.URL absoluteString]);
	NSData				*data = [request HTTPBody];
	char				*raw = data ? (char *) [data bytes] : "";
	
	if (raw && strstr(raw, "cancel=")) {
		//[self denied];
		return NO;
	}
	//if (navigationType != UIWebViewNavigationTypeOther) webview.alpha = 0.1;
	return YES;
}

- (void)engineDidLogIn:(WBEngine *)engine {
    //[_engine requestAccessToken]; callback
    UIWebView* authview = [self.authDelegate weiboAuthview];
    authview.delegate = self.authDelegateBackup;
    [self.authDelegate authCallback];
}



#define str62keys @"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
/**
 * 62进制值转换为10进制
 * @param {String} str62 62进制值
 * @return {String} 10进制值
 */
+(NSString*) str62to10:(NSString*)str62
{
    long long i10 = 0;
	for (int i = 0; i < str62.length; i++)
	{
        NSRange range;
        range.location = i;
        range.length = 1;
		NSString* s = [str62 substringWithRange:range];
        int loc = [str62keys rangeOfString:s].location;
        if (loc >= 0) {
            i10 = i10 * 62 + loc;
        }
	}
	return [NSString stringWithFormat:@"%lld", i10];
}
/**
 * 10进制值转换为62进制
 * @param {String} int10 10进制值
 * @return {String} 62进制值
 */
+(NSString*) int10to62:(NSString*)int10s
{
    NSMutableString* s62 = [[[NSMutableString alloc] init] autorelease];
    long long int10 = [int10s longLongValue];
	long long r = 0;
	while (int10 != 0 && s62.length < 100) {
		r = int10 % 62;
        NSRange range;
        range.location = r;
        range.length = 1;
        [s62 insertString:[str62keys substringWithRange:range] atIndex:0];
		int10 = int10 / 62;
	}
	return s62;
}

/**
 * URL字符转换为mid
 * @param {String} url 微博URL字符，如 "wr4mOFqpbO"
 * @return {String} 微博mid，如 "201110410216293360"
 */
+(NSString*) url2mid:(NSString*)url
{
    NSMutableString* mid = [[[NSMutableString alloc] init] autorelease];
    // 3413794443243803 -- y5MR6dBRp
	for (int i = url.length - 4; i > -4; i = i - 4)	//从最后往前以4字节为一组读取URL字符
	{
		int offset1 = i < 0 ? 0 : i;
		int offset2 = i + 4;
        NSRange range;
        range.location = offset1;
        range.length = offset2-offset1;
		NSString* strk = [url substringWithRange:range];
        
		NSMutableString* strx = [[[NSMutableString alloc] initWithString:[SinaWeibo str62to10:strk]] autorelease];
		if (offset1 > 0)	//若不是第一组，则不足7位补0 
		{
			while (strx.length < 7)
			{
				[strx insertString:@"0" atIndex:0];
			}
		}
        
		[mid insertString:strx atIndex:0];
	}
    
	return mid;
}
/**
 * mid转换为URL字符
 * @param {String} mid 微博mid，如 "201110410216293360"
 * @return {String} 微博URL字符，如 "wr4mOFqpbO"
 */
+(NSString*) mid2url:(NSString*)mid
{
    if(!mid) 
    {
        return mid;
    }
    
    if ([mid rangeOfRegex:@"^\\d+$"].location == NSNotFound) 
    {
        return mid;
    }

	NSMutableString* url = [[[NSMutableString alloc] init ] autorelease];
    
	for (int i = mid.length - 7; i > -7; i = i - 7)	//从最后往前以7字节为一组读取mid
	{
		int offset1 = i < 0 ? 0 : i;
		int offset2 = i + 7;
        NSRange range;
        range.location = offset1;
        range.length = offset2-offset1;
		NSString* num = [mid substringWithRange:range];
        
		num = [SinaWeibo int10to62:num];
		[url insertString:num atIndex:0];
	}
    
	return url;
}



-(void) short_url_shorten:(NSString*)long_url  delegate:(id<WeiboShortUrlShortenDelegate>)delegate{// 长链转短链
    [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_WeiboShortUrlShortenDelegate;
    
    NSString* short_url = [[UserDataforUrlmap sharedInstance] getShortUrlByLongUrl:long_url];
    if (!short_url || short_url.length<=0) { // 短网址 无效
        if (long_url && [long_url startswith:@"http://t.cn/"]) { // 长网址 就是 短的
            short_url = long_url; // http://t.cn/
        }
    }
    if (short_url && short_url.length>0) {
        [self.getWeiboShortUrlShortenDelegate getWeiboShortUrlShortenDelegateCallback:self url_short:short_url url_long:long_url result:true];
        return;
    }    
    if (!long_url || long_url.length<=0) {
        [self.getWeiboShortUrlShortenDelegate getWeiboShortUrlShortenDelegateError:self];
        return;
    }
    _apiType = API_TYPE_WeiboShortUrlShortenDelegate;
    [_engine api_getShortUrlShorten:long_url];
}

-(void) short_url_shortenArrayMax20:(NSMutableArray*)long_url_array delegate:(id<WeiboShortUrlShortenArrayDelegate>)delegate { // 长链转短链
    [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_WeiboShortUrlShortenArrayDelegate;
    assert(long_url_array.count <= 20);
    
    BOOL allFound = YES;
    NSMutableDictionary* dict = [NSMutableDictionary dictionary]; // WeiboUrlShortenResult
    for (NSString* long_url in long_url_array) {
        NSString* short_url = [[UserDataforUrlmap sharedInstance] getShortUrlByLongUrl:long_url];
        if (!short_url || short_url.length<=0) { // 短网址 无效
            if (long_url && [long_url startswith:@"http://t.cn/"]) { // 长网址 就是 短的
                short_url = long_url; // http://t.cn/
            }
        }
        // 结果。。。
        if (short_url && short_url.length>0) {
            WeiboUrlShortenResult* value = [[[WeiboUrlShortenResult alloc] initWithUrlLong:long_url urlShort:short_url result:YES] autorelease];
            [dict setValue:value forKey:long_url];
        } else {
            allFound = NO;
        }
        // 输入错误
        if (!long_url || long_url.length<=0) {
            [self.getWeiboShortUrlShortenArrayDelegate getWeiboShortUrlShortenArrayDelegateError:self];
            return;
        }
    }
    
    if (allFound) {
        [self.getWeiboShortUrlShortenArrayDelegate getWeiboShortUrlShortenArrayDelegateCallback:self long2short_dict:dict];
        return ;
    }
    _apiType = API_TYPE_WeiboShortUrlShortenArrayDelegate;
    [_engine api_getShortUrlShortenArray:long_url_array];
}


-(void) short_url_clicksArrayMax20:(NSMutableArray*)short_url_array delegate:(id<WeiboShortUrlClicksArrayDelegate>)delegate  
                      forceConnect:(BOOL)force {// 获取短链接的总点击数 
    [self setOnetimeDelegate: delegate];
    assert(short_url_array.count <= 20);
    
    if (force) {
        _apiType = API_TYPE_WeiboShortUrlClicksArrayDelegate;
        [_engine api_getShortUrlClicksArray:short_url_array];
        return;
    }
    
    BOOL haveOneNotVisited = FALSE;
    NSMutableDictionary* dict = [NSMutableDictionary dictionary];
    for (NSString* short_url in short_url_array) {
        if ([SinaWeibo isVisitedbyUrlShort:short_url]) {
            NSString* long_url = [[UserDataforUrlmap sharedInstance] getLongUrlByShortUrl:short_url];
            int count = [[UserDataforClicksbak sharedInstance] getClicks:long_url];
            if (long_url && count>=0) {
                WeiboUrlClicksResult* value = [[[WeiboUrlClicksResult alloc] initWithUrlLong:long_url urlShort:short_url clicks:count] autorelease];
                [dict setValue:value forKey:short_url];
            } else {
                haveOneNotVisited = TRUE;
            }
        } else {
            haveOneNotVisited = TRUE;
        }
        
        // 输入错误
        if (!short_url || short_url.length<=0) {
            [self.getWeiboShortUrlClicksArrayDelegate getWeiboShortUrlClicksArrayError:self];
            return;
        }
    }
    
    
    if (!haveOneNotVisited) {
        [self.getWeiboShortUrlClicksArrayDelegate getWeiboShortUrlClicksArrayCallback:self short2clicks_dict:dict];
        return;    
    }    
    _apiType = API_TYPE_WeiboShortUrlClicksArrayDelegate;
    [_engine api_getShortUrlClicksArray:short_url_array];
}

-(void) short_url_clicks:(NSString*)short_url delegate:(id<WeiboShortUrlClicksDelegate>)delegate  forceConnect:(BOOL)force {// 获取短链接的总点击数 
    [self setOnetimeDelegate: delegate];
    
    if (force) {
        _apiType = API_TYPE_WeiboShortUrlClicksDelegate;
        [_engine api_getShortUrlClicks:short_url];
        return;
    }
    if ([SinaWeibo isVisitedbyUrlShort:short_url]) {

        NSString* long_url = [[UserDataforUrlmap sharedInstance] getLongUrlByShortUrl:short_url];
        int count = [[UserDataforClicksbak sharedInstance] getClicks:long_url];
        if (long_url && count>=0) {
            [self.getWeiboShortUrlClicksDelegate getWeiboShortUrlClicksCallback:self url_short:short_url url_long:long_url clicks:count];
            return;
        }
    }
    _apiType = API_TYPE_WeiboShortUrlClicksDelegate;
    [_engine api_getShortUrlClicks:short_url];
}



-(void) this_short_url_shorten:(NSString*)long_url
{
    NSString* short_url = [[UserDataforUrlmap sharedInstance] getShortUrlByLongUrl:long_url];
    if (short_url && short_url.length>0) {
        [self getWeiboShortUrlShortenDelegateCallback:self url_short:short_url url_long:long_url result:true];
        return;
    } else {
        [step_ShortUrl setDelegateNilAll];
        YRelease(step_ShortUrl)
        step_ShortUrl = [[SinaWeibo alloc] init];
        [step_ShortUrl short_url_shorten:long_url delegate:self];
    }
}

-(void) short_url_clicks_bylong:(NSString *)long_url delegate:(id<WeiboShortUrlClicksDelegate>)delegate  forceConnect:(BOOL)force {
    [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_short_url_clicks_bylong;
    bak_force = force;
    // 分两步走。。。    
    if (!long_url || long_url.length<=0) {
        [self getWeiboShortUrlShortenDelegateError:self];
        return;
    }
    [self this_short_url_shorten:long_url];
}
-(void) short_url_clicks_bylongArrayMax20:(NSMutableArray*)long_url_array delegate:(id<WeiboShortUrlClicksArrayDelegate>)delegate forceConnect:(BOOL)force {
    [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_short_url_clicksArray_bylong;
    bak_force = force;
    // 分两步走。。。    
    [step_ShortUrl setDelegateNilAll];
    YRelease(step_ShortUrl)
    step_ShortUrl = [[SinaWeibo alloc] init];
    [step_ShortUrl short_url_shortenArrayMax20:long_url_array delegate:self];
}
-(void) short_url_share_counts_bylong:(NSString*)long_url delegate:(id<WeiboShortUrlShareCountsDelegate>)delegate { // 获取短链接在微博上的微博分享数 
     [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_short_url_share_counts_bylong;
    // 分两步走。。。  
    if (!long_url || long_url.length<=0) {
        [self getWeiboShortUrlShortenDelegateError:self];
        return;
    }
    [self this_short_url_shorten:long_url];
}
-(void) short_url_share_statuses_bylong:(NSString*)long_url max_id:(long long)max_id count:(int)count delegate:(id<WeiboShortUrlShareStatusDelegate>)delegate { // 获取包含指定单个短链接的最新微博内容 
    [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_short_url_share_statuses_bylong;
    bak_max_id = max_id;
    bak_count = count;
    // 分两步走。。。   
    if (!long_url || long_url.length<=0) {
        [self getWeiboShortUrlShortenDelegateError:self];
        return;
    }
    [self this_short_url_shorten:long_url];
}
-(void) short_url_comment_counts_bylong:(NSString*)long_url delegate:(id<WeiboShortUrlCommentCountsDelegate>)delegate { // 获取短链接在微博上的微博评论数 
     [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_short_url_comment_counts_bylong;
    // 分两步走。。。 
    if (!long_url || long_url.length<=0) {
        [self getWeiboShortUrlShortenDelegateError:self];
        return;
    }
    [self this_short_url_shorten:long_url];
}
-(void) short_url_comment_comments_bylong:(NSString*)long_url max_id:(long long)max_id count:(int)count delegate:(id<WeiboShortUrlCommentCommentsDelegate>)delegate { // 获取包含指定单个短链接的最新微博评论 
     [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_short_url_comment_comments_bylong;
    bak_max_id = max_id;
    bak_count = count;
    // 分两步走。。。   
    if (!long_url || long_url.length<=0) {
        [self getWeiboShortUrlShortenDelegateError:self];
        return;
    }
    [self this_short_url_shorten:long_url];
}









-(void) getWeiboShortUrlShortenArrayDelegateError:(WeiboBase*)weibo {
    [step_ShortUrl setDelegateNilAll];
    YRelease(step_ShortUrl)
    if (_apiType == API_TYPE_short_url_clicksArray_bylong) {
        [self.getWeiboShortUrlClicksArrayDelegate getWeiboShortUrlClicksArrayError:self];
    }
}
-(void) getWeiboShortUrlShortenArrayDelegateCallback:(WeiboBase*)weibo long2short_dict:(NSMutableDictionary*)dict {
    // url_long -> WeiboUrlShortenResult
    [step_ShortUrl setDelegateNilAll];
    YRelease(step_ShortUrl)
    if (_apiType == API_TYPE_short_url_clicksArray_bylong) { // 分两步走。。。第二步
        NSMutableArray* array = [NSMutableArray array];
        for (WeiboUrlShortenResult* temp in dict.objectEnumerator) {
            [array addObject:temp.url_short];
        }
        [self short_url_clicksArrayMax20:array delegate:self.getWeiboShortUrlClicksArrayDelegate forceConnect:bak_force];
    }
}

-(void) getWeiboShortUrlShortenDelegateError:(WeiboBase*)weibo {
    
    [step_ShortUrl setDelegateNilAll];
    YRelease(step_ShortUrl)
    if (_apiType == API_TYPE_WeiboShortUrlShortenDelegate) {
        if (self.getWeiboShortUrlShortenDelegate == nil/*调到这里，一次性delegate已经消耗了，等于self，但是等于nil了*/) {
            if (short_url_shorten_autorelease) [self release];
            short_url_shorten_autorelease = false;
        } else {
            assert(false);
        }
    }
    
    if (_apiType == API_TYPE_short_url_clicks_bylong) {// 分两步走。。。第二步
        [self.getWeiboShortUrlClicksDelegate getWeiboShortUrlClicksError:self];
    }    
    if (_apiType == API_TYPE_short_url_share_counts_bylong) {
        [self.getWeiboShortUrlShareCountsDelegate getWeiboShortUrlShareCountsDelegateError:self];
    }
    if (_apiType == API_TYPE_short_url_share_statuses_bylong) {
        [self.getWeiboShortUrlShareStatusDelegate getWeiboShortUrlShareStatusDelegateError:self];
    }
    if (_apiType == API_TYPE_short_url_comment_counts_bylong) {
        [self.getWeiboShortUrlCommentCountsDelegate getWeiboShortUrlCommentCountsDelegateError:self];
    }
    if (_apiType == API_TYPE_short_url_comment_comments_bylong) {
        [self.getWeiboShortUrlCommentCommentsDelegate getWeiboShortUrlCommentCommentsDelegateError:self];
    }
}
-(void) getWeiboShortUrlShortenDelegateCallback:(WeiboBase*)weibo url_short:(NSString*)url_short url_long:(NSString *)url_long  result:(bool)result {
    
    [step_ShortUrl setDelegateNilAll];
    YRelease(step_ShortUrl)
    if (_apiType == API_TYPE_WeiboShortUrlShortenDelegate) {        
        if (self.getWeiboShortUrlShortenDelegate == nil/*调到这里，一次性delegate已经消耗了，等于self，但是等于nil了*/) {
            if (short_url_shorten_autorelease) [self release];
            short_url_shorten_autorelease = false;
            if (url_short && url_short.length>0) {
                [SinaWeibo short_url_click:url_short];
            }
        } else {
            assert(false);
        }
    }
    
    if (_apiType == API_TYPE_short_url_clicks_bylong) {// 分两步走。。。第二步
        if (result) {           
            [self short_url_clicks:url_short delegate:self.getWeiboShortUrlClicksDelegate forceConnect:bak_force];
        } else {
            [self.getWeiboShortUrlClicksDelegate getWeiboShortUrlClicksError:self];
        }
    }
    if (_apiType == API_TYPE_short_url_share_counts_bylong) {
        if (result) {
            _apiType = API_TYPE_WeiboShortUrlShareCountsDelegate;
            [_engine api_getShortUrlShareCounts:url_short];
        } else {
            [self.getWeiboShortUrlShareCountsDelegate getWeiboShortUrlShareCountsDelegateError:self];
        }
    }
    if (_apiType == API_TYPE_short_url_share_statuses_bylong) {
        if (result || ![self isAuthorized]) {
            _apiType = API_TYPE_WeiboShortUrlShareStatusDelegate;
            [_engine api_getShortUrlShareStatuses:url_short max_id:bak_max_id count:bak_count];
        } else {
            [self.getWeiboShortUrlShareStatusDelegate getWeiboShortUrlShareStatusDelegateError:self];
        }
    }
    if (_apiType == API_TYPE_short_url_comment_counts_bylong) {
        if (result) {
            _apiType = API_TYPE_WeiboShortUrlCommentCountsDelegate;
            [_engine api_getShortUrlCommentCounts:url_short];
        } else {
            [self.getWeiboShortUrlCommentCountsDelegate getWeiboShortUrlCommentCountsDelegateError:self];
        }
    }
    if (_apiType == API_TYPE_short_url_comment_comments_bylong) {
        if (result) {
            _apiType = API_TYPE_WeiboShortUrlCommentCommentsDelegate;
            [_engine api_getShortUrlCommentComments:url_short max_id:bak_max_id count:bak_count];
        } else {
            [self.getWeiboShortUrlCommentCommentsDelegate getWeiboShortUrlCommentCommentsDelegateError:self];
        }
    }
}




-(void) short_url_share_counts:(NSString*)short_url delegate:(id<WeiboShortUrlShareCountsDelegate>)delegate{// 获取短链接在微博上的微博分享数 
    [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_WeiboShortUrlShareCountsDelegate;
    [_engine api_getShortUrlShareCounts:short_url];
}
-(void) short_url_share_statuses:(NSString*)short_url max_id:(long long)max_id count:(int)count delegate:(id<WeiboShortUrlShareStatusDelegate>)delegate{// 获取包含指定单个短链接的最新微博内容 
    if (![self isAuthorized]) {
        [delegate getWeiboShortUrlShareStatusDelegateError:self];
        return;
    }
    [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_WeiboShortUrlShareStatusDelegate;
    [_engine api_getShortUrlShareStatuses:short_url max_id:max_id count:count];
}
-(void) short_url_comment_counts:(NSString*)short_url delegate:(id<WeiboShortUrlCommentCountsDelegate>)delegate {// 获取短链接在微博上的微博评论数 
    [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_WeiboShortUrlCommentCountsDelegate;
    [_engine api_getShortUrlCommentCounts:short_url];
}
-(void) short_url_comment_comments:(NSString*)short_url max_id:(long long)max_id count:(int)count delegate:(id<WeiboShortUrlCommentCommentsDelegate>)delegate{// 获取包含指定单个短链接的最新微博评论 
    [self setOnetimeDelegate: delegate];
    _apiType = API_TYPE_WeiboShortUrlCommentCommentsDelegate;
    [_engine api_getShortUrlCommentComments:short_url max_id:max_id count:count];
}
@end
